<template>
  <div>
    <el-form ref="form" :model="logData" label-width="80px" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="logData.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="logData.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="logn">立即登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import axios from 'axios'
export default {
  data() {
    return {
      logData: {
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 18,
            message: "长度在 5 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    logn() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          alert("请输入有效的账号或密码");
          return false;
          }
          this.$req.post("/login", this.logData).then((res) => {
            //解构赋值用两个变量来接受拿到的值
            const { data, meta } = res.data;
            if (meta.status == 400) {
              this.$message({
                showClose: true,
                message: "错了哦，登录失败",
                type: "error",
              });
            } else if (meta.status == 200) {
              this.$store.commit("userchange", data);
              this.$message({
                showClose: true,
                message: "恭喜你，登录成功",
                type: "success",
              });
              // 登录成功后，进行路由跳转
              this.$router.push({ path: "/home" });
            } else {
              alert("未知");
            }
          });
        
      });
    },
  },
};
</script>

<style>
</style>